package com.mine.modules.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mine.common.domain.dto.LoginModel;
import com.mine.common.domain.vo.Result;
import com.mine.modules.sys.domain.dto.RoleDto;
import com.mine.modules.sys.domain.vo.MenuOption;
import com.mine.modules.sys.domain.vo.SysPermissionTree;
import com.mine.modules.sys.domain.vo.TreeModel;
import com.mine.modules.sys.entity.SysPermission;
import com.mine.modules.sys.entity.SysRolePermission;
import com.mine.modules.sys.service.ISysPermissionService;
import com.mine.modules.sys.service.ISysRolePermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限表 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-10-09
 */
@Slf4j
@Api(tags = "菜单管理")
@RestController
@RequestMapping("/sys/menu")
@RequiredArgsConstructor
public class SysPermissionController {

    private final ISysPermissionService sysPermissionService;

    private final ISysRolePermissionService sysRolePermissionService;

    /**
     * 加载数据节点
     *
     */
    @ApiOperation("全部菜单")
    @RequestMapping(value = "/listAll", method = RequestMethod.GET)
    public Result<List<MenuOption>> listAll(@RequestParam(value = "keywords", required = false) String keywords, HttpServletRequest req) {
        return sysPermissionService.listAll(keywords, req);
    }

    /**
     * 加载数据节点
     */
    @ApiOperation("查询菜单树形列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<List<SysPermissionTree>> list(@RequestParam(value = "keywords", required = false) String keywords) {
        return sysPermissionService.lists(keywords);
    }

    /**
     * 系统菜单列表(一级菜单)
     */
    @ApiOperation("一级菜单列表")
    @RequestMapping(value = "/getSystemMenuList", method = RequestMethod.GET)
    public Result<List<SysPermissionTree>> getSystemMenuList() {
        return sysPermissionService.getSystemMenuList();
    }

    /**
     * 查询子菜单
     */
    @ApiOperation("查询子菜单")
    @RequestMapping(value = "/getSystemSubmenu", method = RequestMethod.GET)
    public Result<List<SysPermissionTree>> getSystemSubmenu(@RequestParam("parentId") String parentId) {
        return sysPermissionService.getSystemSubmenu(parentId);
    }

    /**
     * 查询子菜单
     *
     * @param parentIds 父ID（多个采用半角逗号分割）
     * @return 返回 key-value 的 Map
     */
    @ApiOperation("批量查询子菜单")
    @GetMapping("/getSystemSubmenuBatch")
    public Result<?> getSystemSubmenuBatch(@RequestParam("parentIds") String parentIds) {
        return sysPermissionService.getSystemSubmenuBatch(parentIds);
    }

    /**
     * 查询用户拥有的菜单权限和按钮权限
     */
    @ApiOperation("token查询用户拥有的菜单权限")
    @RequestMapping(value = "/getUserPermissionByToken", method = RequestMethod.GET)
    public Result<?> getUserPermissionByToken(HttpServletRequest request) {
        return sysPermissionService.getUserPermissionByToken(request);
    }

    /**
     * 【vue3专用】获取
     * 1、查询用户拥有的按钮/表单访问权限
     * 2、所有权限 (菜单权限配置)
     * 3、系统安全模式 (开启则online报表的数据源必填)
     */
    @RequestMapping(value = "/getPermCode", method = RequestMethod.GET)
    public Result<?> getPermCode() {
        return sysPermissionService.getPermCode();
    }

    /**
     * 添加菜单
     */
    @ApiOperation("添加菜单")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result<SysPermission> add(SysPermission permission) {
        return sysPermissionService.add(permission);
    }

    /**
     * 编辑菜单
     */
    @ApiOperation("编辑菜单")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result<SysPermission> edit(SysPermission permission) {
        return sysPermissionService.edit(permission);
    }

    /**
     * 检测菜单路径是否存在
     */
    @RequestMapping(value = "/checkPermDuplication", method = RequestMethod.GET)
    public Result<String> checkPermDuplication(@RequestParam(name = "id", required = false) String id, @RequestParam(name = "url") String url, @RequestParam(name = "alwaysShow") Boolean alwaysShow) {
        return sysPermissionService.checkPermDuplications(id, url, alwaysShow);
    }

    /**
     * 删除菜单
     */
    @ApiOperation("删除菜单")
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        return sysPermissionService.delete(id);
    }

    /**
     * 批量删除菜单
     */
    @ApiOperation("批量删除菜单")
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        return sysPermissionService.deleteBatch(ids);
    }

    /**
     * 获取全部的权限树
     */
    @ApiOperation("获取全部菜单树")
    @RequestMapping(value = "/queryTreeList", method = RequestMethod.GET)
    public Result<Map<String, Object>> queryTreeList() {
        return sysPermissionService.queryTreeList();
    }

    /**
     * 异步加载数据节点 [接口是废的,没有用到]
     */
    @ApiOperation("异步获取菜单树")
    @RequestMapping(value = "/queryListAsync", method = RequestMethod.GET)
    public Result<List<TreeModel>> queryAsync(@RequestParam(name = "pid", required = false) String parentId) {
        return sysPermissionService.queryAsync(parentId);
    }

    /**
     * 查询角色授权
     */
    @ApiOperation("查询角色授权")
    @RequestMapping(value = "/queryRolePermission", method = RequestMethod.GET)
    public Result<List<String>> queryRolePermission(@RequestParam(name = "roleId", required = true) String roleId) {
        Result<List<String>> result = new Result<>();
        try {
            List<SysRolePermission> list = sysRolePermissionService.list(new QueryWrapper<SysRolePermission>().lambda().eq(SysRolePermission::getRoleId, roleId));
            result.setResult(list.stream().map(sysRolePermission -> String.valueOf(sysRolePermission.getPermissionId())).collect(Collectors.toList()));
            result.success("查询成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 保存角色授权
     */
    @ApiOperation("保存角色授权")
    @RequestMapping(value = "/saveRolePermission", method = RequestMethod.POST)
    public Result<String> saveRolePermission(RoleDto roleDto) {
        long start = System.currentTimeMillis();
        Result<String> result = new Result<>();
        try {
            String roleId = roleDto.getRoleId();
            String permissionIds = roleDto.getPermissionIds();
            String lastPermissionIds = roleDto.getLastpermissionIds();
            this.sysRolePermissionService.saveRolePermission(roleId, permissionIds, lastPermissionIds);
            LoginModel loginUser = (LoginModel) SecurityUtils.getSubject().getPrincipal();
            result.success("操作成功！");
            log.info("======角色授权成功=====耗时:{}毫秒", System.currentTimeMillis() - start);
        } catch (Exception e) {
            result.error500("授权失败！");
            log.error(e.getMessage(), e);
        }
        return result;
    }


}
